package com.axialproject.health.exchange.democommunity;

import com.axialproject.health.exchange.EMF;
import com.axialproject.health.exchange.Router;
import com.axialproject.health.exchange.Record;
import com.axialproject.health.exchange.democommunity.entity.CommunityRecord;
import com.axialproject.health.exchange.entity.Patient;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;

public class RouterImpl implements Router {

    private static final Logger log = Logger.getLogger(RouterImpl.class.getName());

    @Override
    public void sendRecord(Patient patient, Record record) {
        // String patientName = patient.getName();
        // String patientDob = patient.getDob();
        // String patientGender = patient.getGender().getName();
        // String patientRace = patient.getRace().getName();

 
        for (int i = 0; i < record.getTestNames().size(); i++) {
            CommunityRecord cr = new CommunityRecord();
            cr.setPatientName(patient.getName());
            cr.setPatientAddress(patient.getAddress());
            cr.setPatientDob(patient.getDob());
            cr.setPatientGender(patient.getGender().getName());
            cr.setPatientRace(patient.getRace().getName());
            cr.setTestDate(record.getStart());
            cr.setTestName(record.getTestNames().get(i));
            cr.setTestResult(record.getTestResults().get(i));
            cr.setTestResultUnit(record.getTestResultUnits().get(i));
            cr.setTestResultNormalRange(record.getTestResultNormalRanges().get(i));
            cr.setTestNote(record.getDescription());
            
            // VERY UGLY GAE Hack -- you can only operate on a root entity once per transaction!
            EntityManager em = EMF.get().createEntityManager();
            try {
                em.persist(cr);
            } catch (Exception e) {
                log.log(Level.SEVERE, e.getMessage(), e);
            } finally {
                em.close();
            }
        }

    }


}
